const { query } = require('../database/connection');

class User {
  /**
   * 根据手机号查找用户
   * @param {string} phone 手机号
   * @returns {Object|null} 用户信息
   */
  static async findByPhone(phone) {
    try {
      const results = await query(
        'SELECT * FROM users WHERE phone = ? LIMIT 1',
        [phone]
      );
      return results.length > 0 ? results[0] : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID查找用户
   * @param {number} id 用户ID
   * @returns {Object|null} 用户信息
   */
  static async findById(id) {
    try {
      const results = await query(
        'SELECT * FROM users WHERE id = ? LIMIT 1',
        [id]
      );
      return results.length > 0 ? results[0] : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  /**
   * 创建或更新用户信息
   * @param {Object} userData 用户数据
   * @returns {Object} 操作结果
   */
  static async upsert(userData) {
    try {
      const existing = await this.findByPhone(userData.phone);
      const username = userData.username || userData.phone || null;
      
      if (existing) {
        // 更新现有用户
        await query(
          `UPDATE users SET 
           username = ?, token = ?, refresh_token = ?, nickname = ?, avatar_url = ?,
           city = ?, province = ?, latitude = ?, longitude = ?, updated_at = NOW()
           WHERE phone = ?`,
          [
            username, userData.token, userData.refresh_token, userData.nickname,
            userData.avatar_url, userData.city, userData.province,
            userData.latitude, userData.longitude, userData.phone
          ]
        );
        return { action: 'updated', userId: existing.id, phone: userData.phone };
      } else {
        // 创建新用户
        const result = await query(
          `INSERT INTO users 
           (phone, username, token, refresh_token, nickname, avatar_url, city, province, latitude, longitude)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
          [
            userData.phone, username, userData.token, userData.refresh_token,
            userData.nickname, userData.avatar_url, userData.city,
            userData.province, userData.latitude, userData.longitude
          ]
        );
        return { action: 'created', userId: result.insertId, phone: userData.phone };
      }
    } catch (error) {
      console.error('用户信息保存失败:', error);
      throw error;
    }
  }

  /**
   * 更新用户token
   * @param {string} phone 手机号
   * @param {string} token 访问token
   * @param {string} refreshToken 刷新token
   * @returns {boolean} 更新结果
   */
  static async updateToken(phone, token, refreshToken = null) {
    try {
      const result = await query(
        'UPDATE users SET token = ?, refresh_token = ?, updated_at = NOW() WHERE phone = ?',
        [token, refreshToken, phone]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新用户token失败:', error);
      throw error;
    }
  }

  /**
   * 更新用户自定义头像
   * @param {string} phone 手机号
   * @param {string} customAvatar 自定义头像路径
   * @returns {boolean} 更新结果
   */
  static async updateCustomAvatar(phone, customAvatar) {
    try {
      const result = await query(
        'UPDATE users SET custom_avatar = ?, updated_at = NOW() WHERE phone = ?',
        [customAvatar, phone]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新用户自定义头像失败:', error);
      throw error;
    }
  }

  /**
   * 验证用户token
   * @param {string} token 访问token
   * @returns {Object|null} 用户信息
   */
  static async verifyToken(token) {
    try {
      const results = await query(
        'SELECT * FROM users WHERE token = ? LIMIT 1',
        [token]
      );
      return results.length > 0 ? results[0] : null;
    } catch (error) {
      // 当数据库缺少 token 字段时（ER_BAD_FIELD_ERROR 1054），优雅降级为未找到用户
      if (error?.code === 'ER_BAD_FIELD_ERROR' || error?.errno === 1054) {
        console.warn("[verifyToken] 数据表 'users' 缺少 'token' 字段，已降级为未登录。请执行表结构升级以启用基于 token 的关联。");
        return null;
      }
      console.error('验证用户token失败:', error);
      throw error;
    }
  }
}

module.exports = User;
